﻿using Autofac;
using Loong.BackgroundJobs;
using Loong.Dependency;
using Loong.Domain.Uow;
using Loong.EntityFrameworkCore;
using Loong.EntityFrameworkCore.Uow;
using Loong.Modules;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Loong.EfCoreRepository.MySql
{
    public sealed class MySqlEfCoreRepositoryModule : Module, ILoongModule
    {
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext<LoongDbContext>(options =>
            {
                options.UseMySql(configuration.GetSection(ConnectionStringOptions.SectionName)[ConnectionStringOptions.ConnectionName]);
            },
            ServiceLifetime.Transient,
            ServiceLifetime.Transient);

            services.Configure<ConnectionStringOptions>(configuration.GetSection(ConnectionStringOptions.SectionName));
        }

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyByConvention(ThisAssembly);
            builder.RegisterType(typeof(UnitOfWorkDbContextProvider<LoongDbContext>)).As(typeof(IDbContextProvider<LoongDbContext>)).InstancePerDependency();
            builder.RegisterType<BackgroundJobStore>().As<IBackgroundJobStore>().InstancePerLifetimeScope();
        }

        public void Initialize()
        {
            using (var scope = IocManager.IocContainer.BeginLifetimeScope())
            {
                scope.Resolve<LoongDbContext>().Database.Migrate();
            }
        }

        public void Shutdown()
        {
        }
    }
}
